<template>
  <el-dialog 
    title="POS设备柜组权限管理" 
    :visible.sync="dialogVisible" 
    width="800px" 
    append-to-body
    @close="handleClose"
  >
    <div class="device-permission">
      <!-- 设备信息 -->
      <el-card header="设备信息" style="margin-bottom: 20px;">
        <div class="device-info">
          <div class="info-item">
            <label>设备编码：</label>
            <span>{{ deviceData.deviceCode }}</span>
          </div>
          <div class="info-item">
            <label>设备名称：</label>
            <span>{{ deviceData.deviceName }}</span>
          </div>
          <div class="info-item">
            <label>设备类型：</label>
            <dict-tag :options="dict.type.pos_device_type" :value="deviceData.deviceType"/>
          </div>
          <div class="info-item">
            <label>当前状态：</label>
            <dict-tag :options="dict.type.sys_normal_disable" :value="deviceData.status"/>
          </div>
        </div>
      </el-card>

      <!-- 权限管理 -->
      <el-card header="柜组权限管理">
        <div class="permission-section">
          <!-- 权限类型选择 -->
          <div class="permission-type">
            <el-radio-group v-model="permissionType" @change="handlePermissionTypeChange">
              <el-radio label="fixed">固定权限</el-radio>
              <el-radio label="mobile">移动权限</el-radio>
              <el-radio label="temporary">临时权限</el-radio>
            </el-radio-group>
            <el-button 
              type="text" 
              size="small" 
              @click="showPermissionHelp"
              style="margin-left: 20px;"
            >
              <i class="el-icon-question"></i> 权限说明
            </el-button>
          </div>

          <!-- 固定权限 -->
          <div v-if="permissionType === 'fixed'" class="permission-content">
            <div class="section-header">
              <span>固定柜组权限</span>
              <el-button size="mini" type="primary" @click="selectAllGroups">全选</el-button>
            </div>
            <el-checkbox-group v-model="fixedGroups" @change="handleFixedGroupChange">
              <div class="group-list">
                <el-checkbox 
                  v-for="group in availableGroups" 
                  :key="group.groupId"
                  :label="group.groupId"
                  :disabled="group.status === '1'"
                >
                  <div class="group-item">
                    <span class="group-name">{{ group.groupName }}</span>
                    <el-tag size="mini" type="info">{{ group.groupCode }}</el-tag>
                    <span class="group-type">{{ getGroupTypeName(group.groupType) }}</span>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>

          <!-- 移动权限 -->
          <div v-if="permissionType === 'mobile'" class="permission-content">
            <div class="section-header">
              <span>移动柜组权限</span>
              <el-button size="mini" type="success" @click="selectAllMobileGroups">全选</el-button>
            </div>
            <el-checkbox-group v-model="mobileGroups" @change="handleMobileGroupChange">
              <div class="group-list">
                <el-checkbox 
                  v-for="group in availableGroups" 
                  :key="group.groupId"
                  :label="group.groupId"
                  :disabled="group.status === '1'"
                >
                  <div class="group-item">
                    <span class="group-name">{{ group.groupName }}</span>
                    <el-tag size="mini" type="success">{{ group.groupCode }}</el-tag>
                    <span class="group-type">{{ getGroupTypeName(group.groupType) }}</span>
                    <el-tag size="mini" type="warning">移动</el-tag>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>

          <!-- 临时权限 -->
          <div v-if="permissionType === 'temporary'" class="permission-content">
            <div class="section-header">
              <span>临时柜组权限</span>
              <el-button size="mini" type="warning" @click="addTemporaryPermission">添加临时权限</el-button>
            </div>
            
            <!-- 临时权限列表 -->
            <div class="temporary-list">
              <div 
                v-for="(temp, index) in temporaryPermissions" 
                :key="index"
                class="temporary-item"
              >
                <div class="temporary-header">
                  <el-select v-model="temp.groupId" placeholder="选择柜组" size="small">
                    <el-option
                      v-for="group in availableGroups"
                      :key="group.groupId"
                      :label="group.groupName"
                      :value="group.groupId"
                    />
                  </el-select>
                  <el-date-picker
                    v-model="temp.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    size="small"
                    style="width: 180px;"
                  />
                  <el-date-picker
                    v-model="temp.endTime"
                    type="datetime"
                    placeholder="结束时间"
                    size="small"
                    style="width: 180px;"
                  />
                  <el-button 
                    size="mini" 
                    type="danger" 
                    icon="el-icon-delete"
                    @click="removeTemporaryPermission(index)"
                  >删除</el-button>
                </div>
                <div class="temporary-footer">
                  <el-input
                    v-model="temp.reason"
                    placeholder="权限原因/备注"
                    size="small"
                    style="width: 300px;"
                  />
                  <el-tag 
                    v-if="temp.isActive" 
                    size="mini" 
                    type="success"
                  >生效中</el-tag>
                  <el-tag 
                    v-else-if="temp.isExpired" 
                    size="mini" 
                    type="danger"
                  >已过期</el-tag>
                  <el-tag 
                    v-else 
                    size="mini" 
                    type="info"
                  >未生效</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 权限预览 -->
      <el-card header="权限预览" style="margin-top: 20px;">
        <div class="permission-preview">
          <div class="preview-item">
            <label>固定权限：</label>
            <div class="preview-tags">
              <el-tag 
                v-for="groupId in fixedGroups" 
                :key="groupId"
                type="primary"
                size="small"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ getGroupName(groupId) }}
              </el-tag>
              <span v-if="fixedGroups.length === 0" class="empty-text">无</span>
            </div>
          </div>
          <div class="preview-item">
            <label>移动权限：</label>
            <div class="preview-tags">
              <el-tag 
                v-for="groupId in mobileGroups" 
                :key="groupId"
                type="success"
                size="small"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ getGroupName(groupId) }}
              </el-tag>
              <span v-if="mobileGroups.length === 0" class="empty-text">无</span>
            </div>
          </div>
          <div class="preview-item">
            <label>临时权限：</label>
            <div class="preview-tags">
              <el-tag 
                v-for="(temp, index) in temporaryPermissions" 
                :key="index"
                type="warning"
                size="small"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ getGroupName(temp.groupId) }} ({{ formatTimeRange(temp.startTime, temp.endTime) }})
              </el-tag>
              <span v-if="temporaryPermissions.length === 0" class="empty-text">无</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">保存权限</el-button>
    </div>

    <!-- 权限说明对话框 -->
    <el-dialog
      title="权限类型说明"
      :visible.sync="helpDialogVisible"
      width="600px"
      append-to-body
    >
      <div class="permission-help">
        <div class="help-item">
          <h4>固定权限</h4>
          <p>设备固定绑定到指定柜组，只能收银该柜组的商品。适用于固定位置的POS设备。</p>
        </div>
        <div class="help-item">
          <h4>移动权限</h4>
          <p>设备可以收银多个柜组的商品，支持跨柜组收银。适用于手持移动POS设备。</p>
        </div>
        <div class="help-item">
          <h4>临时权限</h4>
          <p>设备在指定时间段内可以收银指定柜组的商品。适用于临时调配、促销活动等场景。</p>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listGroup } from "@/api/pos/group";
import { getDeviceGroupPermissions, setDeviceGroupPermissions } from "@/api/pos/device";

export default {
  name: "DeviceGroupPermission",
  dicts: ['sys_normal_disable', 'pos_device_type', 'pos_group_type'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    deviceData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      helpDialogVisible: false,
      saving: false,
      permissionType: 'fixed',
      // 可用柜组
      availableGroups: [],
      // 固定权限
      fixedGroups: [],
      // 移动权限
      mobileGroups: [],
      // 临时权限
      temporaryPermissions: []
    };
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) {
        this.loadData();
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    /** 加载数据 */
    async loadData() {
      await Promise.all([
        this.loadAvailableGroups(),
        this.loadDevicePermissions()
      ]);
    },
    
    /** 加载可用柜组 */
    async loadAvailableGroups() {
      try {
        const response = await listGroup({ status: '0' });
        this.availableGroups = response.rows || [];
      } catch (error) {
        this.$modal.msgError("加载可用柜组失败");
      }
    },
    
    /** 加载设备权限 */
    async loadDevicePermissions() {
      try {
        const response = await getDeviceGroupPermissions(this.deviceData.deviceId);
        const data = response.data || {};
        this.fixedGroups = data.fixedGroups || [];
        this.mobileGroups = data.mobileGroups || [];
        this.temporaryPermissions = data.temporaryPermissions || [];
      } catch (error) {
        this.$modal.msgError("加载设备权限失败");
      }
    },
    
    /** 权限类型变化 */
    handlePermissionTypeChange(value) {
      // 可以在这里添加一些逻辑
    },
    
    /** 全选固定权限 */
    selectAllGroups() {
      const enabledGroups = this.availableGroups.filter(group => group.status === '0');
      this.fixedGroups = enabledGroups.map(group => group.groupId);
    },
    
    /** 全选移动权限 */
    selectAllMobileGroups() {
      const enabledGroups = this.availableGroups.filter(group => group.status === '0');
      this.mobileGroups = enabledGroups.map(group => group.groupId);
    },
    
    /** 固定权限变化 */
    handleFixedGroupChange(value) {
      // 可以在这里添加一些逻辑
    },
    
    /** 移动权限变化 */
    handleMobileGroupChange(value) {
      // 可以在这里添加一些逻辑
    },
    
    /** 添加临时权限 */
    addTemporaryPermission() {
      this.temporaryPermissions.push({
        groupId: null,
        startTime: null,
        endTime: null,
        reason: '',
        isActive: false,
        isExpired: false
      });
    },
    
    /** 移除临时权限 */
    removeTemporaryPermission(index) {
      this.temporaryPermissions.splice(index, 1);
    },
    
    /** 获取柜组名称 */
    getGroupName(groupId) {
      const group = this.availableGroups.find(g => g.groupId === groupId);
      return group ? group.groupName : '';
    },
    
    /** 获取柜组类型名称 */
    getGroupTypeName(groupType) {
      const dict = this.dict.type.pos_group_type.find(item => item.value === groupType);
      return dict ? dict.label : groupType;
    },
    
    /** 格式化时间范围 */
    formatTimeRange(startTime, endTime) {
      if (!startTime || !endTime) return '';
      const start = this.parseTime(startTime, '{m}-{d} {h}:{i}');
      const end = this.parseTime(endTime, '{m}-{d} {h}:{i}');
      return `${start} ~ ${end}`;
    },
    
    /** 显示权限说明 */
    showPermissionHelp() {
      this.helpDialogVisible = true;
    },
    
    /** 保存权限 */
    async handleSave() {
      this.saving = true;
      try {
        const permissionData = {
          deviceId: this.deviceData.deviceId,
          fixedGroups: this.fixedGroups,
          mobileGroups: this.mobileGroups,
          temporaryPermissions: this.temporaryPermissions
        };
        
        await setDeviceGroupPermissions(permissionData);
        this.$modal.msgSuccess("权限保存成功");
        this.$emit('refresh');
        this.handleClose();
      } catch (error) {
        this.$modal.msgError("权限保存失败");
      } finally {
        this.saving = false;
      }
    },
    
    /** 关闭对话框 */
    handleClose() {
      this.dialogVisible = false;
      this.permissionType = 'fixed';
      this.fixedGroups = [];
      this.mobileGroups = [];
      this.temporaryPermissions = [];
    }
  }
};
</script>

<style scoped>
.device-permission {
  padding: 10px 0;
}

.device-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.info-item label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.permission-section {
  padding: 15px 0;
}

.permission-type {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.permission-content {
  margin-top: 15px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header span {
  font-weight: 600;
  color: #303133;
}

.group-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

.group-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f5f7fa;
}

.group-item:last-child {
  border-bottom: none;
}

.group-name {
  font-weight: 500;
  color: #303133;
}

.group-type {
  font-size: 12px;
  color: #909399;
}

.temporary-list {
  max-height: 300px;
  overflow-y: auto;
}

.temporary-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 10px;
  background: #fafafa;
}

.temporary-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.temporary-footer {
  display: flex;
  align-items: center;
  gap: 10px;
}

.permission-preview {
  padding: 15px 0;
}

.preview-item {
  margin-bottom: 15px;
}

.preview-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
}

.preview-tags {
  min-height: 32px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fafafa;
}

.empty-text {
  color: #c0c4cc;
  font-style: italic;
}

.permission-help {
  padding: 10px 0;
}

.help-item {
  margin-bottom: 20px;
}

.help-item h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.help-item p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.dialog-footer {
  text-align: right;
}
</style>
